import React, { useState, useEffect } from 'react';
import request from '../../../http';
import moment from 'moment';
import { DatePicker, Space, Form, Modal } from 'antd';
import { Select } from 'antd';
import { Button, Menu, Dropdown, Input } from 'antd';
const { RangePicker } = DatePicker;
import { Table, Upload } from 'antd';
import { history } from 'umi';
import { InfoCircleOutlined } from '@ant-design/icons';
const { Option } = Select;
import '../work/addWork.css';
import { EditorState, convertToRaw } from 'draft-js';
import { Editor } from 'react-draft-wysiwyg';
import draftToHtml from 'draftjs-to-html';
import htmlToDraft from 'html-to-draftjs';
import draftToMarkdown from 'draftjs-to-markdown'; //获取编辑框得内容
// 冯小建--下发作业

const columns = [
  {
    title: '发布时间',
    dataIndex: 'release_time',
    width: 140,
  },
  {
    title: '项目名字',
    dataIndex: 'address',
    width: 120,
  },
  {
    title: '作业主题',
    dataIndex: 'address',
  },
  {
    title: '作业类型',
    dataIndex: 'address',
    width: 90,
  },
  {
    title: '实训老师',
    dataIndex: 'address',
    width: 90,
  },
  {
    title: '计划完成时间',
    dataIndex: 'release_time',
    width: 140,
  },
  {
    title: '小组',
    dataIndex: 'address',
  },
  {
    title: '学生总数',
    dataIndex: 'address',
    width: 90,
  },
  {
    title: '待提交',
    dataIndex: 'address',
    width: 80,
  },
  {
    title: '待批复',
    dataIndex: 'address',
    width: 80,
  },
  {
    title: '已批复',
    dataIndex: 'address',
    width: 80,
  },
  {
    title: '操作',
    key: 'operation',
    dataIndex: 'address',
    fixed: 'right',
    width: 120,
    render: (text, record) => (
      <Space size="middle">
        <a>详情</a>
        <a>删除</a>
      </Space>
    ),
  },
];

const date_list: readonly any[] | undefined = [];
for (let i = 0; i < 100; i++) {
  date_list.push({
    key: i,
    release_time: `2021.06.16 12:1${i}`,
    address: `test ${i}`,
  });
}

const addWork = () => {
  const startFormData = {
    annex_id: 0,
    completion_time: '',
    course_id: 0,
    number: 0,
    p_g_id: '',
    page: 0,
    release_time: '',
    s_id: '',
    submitTime: '',
    teacherId: '',
    type: 0,
    work_content: '',
    work_theme: '',
  };
  const [form] = Form.useForm();
  // 操作老师信息
  const [teacher, setTeachers] = useState();
  // 富文本内容
  const [editorState, setEditorState] = useState();
  const [editorContent, setEditorContent] = useState();
  // 表单内容
  const [submitForm, setSubmitForm] = useState(startFormData);

  // 表单初始查询值
  const [projectName, setProjectName] = useState<any>([]); //项目名
  const [grouptName, setGrouptName] = useState<any>([]); //小组名
  const [studentList, setStudentList] = useState<any>([]); //学生
  const [workType, setWorkType] = useState<any>([]); //作业类型

  // 链接查询
  const [courseId, setCourseId] = useState();
  const [groupId, setGroupId] = useState();
  const [responsibility, setResponsibility] = useState('no');

  // 获取表单初始查询值接口
  const getFormInfo = () => {
    console.log('执行-获取表单初始查询值接口-getFormInfo');
    // 查询项目名
    request
      .post('/homework/teacher/selectCourse_DropDownBox')
      .then((response) => {
        console.log('课程', response);
        // 判断
        if (response.code === 20000) {
          // 成功
          // console.log(response.data);
          setProjectName(response.data); //设置项目名值
        } else {
          alert(response.message);
        }
      })
      .catch((error) => {
        console.log(error);
      });
  };

  const getGroupNames = () => {
    // 查询小组名
    request
      .post('/homework/teacher/selectGroup_DropDownBox', {
        course_id: courseId,
      })
      .then((response) => {
        console.log(response);
        // 判断
        if (response.code === 20000) {
          console.log('小组名');
          setGrouptName(response.data); //设置小组
        } else {
          alert(response.message);
        }
      })
      .catch((error) => {
        console.log(error);
      });
  };

  // 查询学生
  const getStudent = () => {
    request
      .post('/homework/teacher/selectStudent_DropDownBox', {
        p_g_id: groupId,
      })
      .then((response) => {
        console.log(response);
        // 判断
        if (response.code === 20000) {
          console.log('小组名');
          setStudentList(response.data); //设置学生
        } else {
          alert(response.message);
        }
      })
      .catch((error) => {
        console.log(error);
      });
  };

  // 选择项目
  const changeCourse = (course_id) => {
    // console.log(course)
    console.log(course_id);
    setCourseId(course_id);
    getGroupNames();
    // 匹配是否为当前老师
    projectName.map((item, i) => {
      item.id === course_id && setResponsibility(item.responsibility);
    });
    console.log(responsibility);
  };
  // 选择小组
  const changeGroup = (p_g_id) => {
    console.log(p_g_id);
    let gId = '';
    p_g_id &&
      p_g_id.map((item, inde) => {
        gId += item + ',';
      });
    setGroupId(gId);
    getStudent(); //获取学生
  };

  // 上传附件
  const normFile = (e: any) => {
    console.log('Upload event:', e);
    if (Array.isArray(e)) {
      return e;
    }
    return e && e.fileList;
  };

  // 禁止日期
  const disabledDate = (current) => {
    // return current && current < moment().endOf('day');
    return current && current < moment().subtract(1, 'days');
  };

  // 富文本变化
  const onEditorStateChange = (editorState) => {
    // console.log(convertToRaw(editorState.getCurrentContent()))
    setEditorState(editorState);
  };
  //获取内容变化值
  const onEditorChange = (editorContent) => {
    // console.log(JSON.stringify(editorContent));
    setEditorContent(editorContent);
  };

  // 发布作业
  const onFinish = (fieldsValue: any) => {
    const release_time = moment(Date.now()).format('YYYY-MM-DD HH:mm:ss') || ''; //当前时间
    const completion_time = fieldsValue['completion_time']
      ? fieldsValue['completion_time'].format('YYYY-MM-DD HH:mm:ss')
      : '';
    const fileList = fieldsValue['upload'];
    let sId = ''; //学生id
    fieldsValue['s_id'] &&
      fieldsValue['s_id'].map((item, inde) => {
        sId += item + ',';
      });
    let gId = ''; //小组id
    fieldsValue['p_g_id'] &&
      fieldsValue['p_g_id'].map((item, inde) => {
        gId += item + ',';
      });
    const editorContent = draftToMarkdown(
      convertToRaw(editorState.getCurrentContent()),
    );
    const values = {
      // ...fieldsValue,
      release_time: release_time,
      completion_time: completion_time,
      p_g_id: gId,
      s_id: sId,
      course_id: parseInt(fieldsValue['course_id']) || 0,
      work_theme: fieldsValue['work_theme'] || '',
      type: parseInt(fieldsValue['type']) || 0,
      work_content: editorContent || '',
    };
    setSubmitForm(values);
    console.log('Received values of form: ', fieldsValue, values);
    values && showModal();
  };

  // 重置
  const onReset = () => {
    form.resetFields();
  };

  //页面加载
  useEffect(() => {
    // 获取初始查询值
    getFormInfo();
  }, []);

  const [visible, setVisible] = React.useState(false);
  const [confirmLoading, setConfirmLoading] = React.useState(false);
  const [modalText, setModalText] = React.useState('确定要发布吗？');

  const showModal = () => {
    setVisible(true);
  };

  // 发布
  const handleOk = () => {
    setModalText('正在发布...');
    setConfirmLoading(true);
    setTimeout(() => {
      setVisible(false);
      setConfirmLoading(false);
      // 执行发布作业
      request
        .post('/homework/teacher/addHomework', submitForm)
        .then((response) => {
          console.log(response);
          // 判断
          if (response.code === 20000) {
            console.log('发布作业成功');
            Modal.success({
              content: '发布成功！',
            });
            history.push('/teacher/work/arrange');
          } else {
            // alert(response.message);
            Modal.error({
              title: '失败',
              content: response.message,
            });
          }
        })
        .catch((error) => {
          console.log(error);
          Modal.error({
            title: '失败',
            content: '发布作业失败',
          });
        });
    }, 2000);
  };

  const handleCancel = () => {
    console.log('Clicked cancel button');
    setVisible(false);
  };

  return (
    <div>
      <h1>发布作业</h1>

      {/* 查询表单 */}
      <Form
        form={form}
        name="time_related_controls"
        className="absence-form my-form"
        onFinish={onFinish}
        layout="inline"
      >
        <Form.Item
          style={{ width: '90%' }}
          className="form-item"
          name="work_theme"
          label="主题"
          rules={[{ required: true }]}
        >
          <Input placeholder="请录入" />
        </Form.Item>

        <Form.Item
          style={{ width: '28%' }}
          className="form-item"
          name="completion_time"
          label="计划完成时间"
          rules={[{ required: true }]}
        >
          <DatePicker
            disabledDate={disabledDate}
            style={{ width: '100%' }}
            showTime
          />
        </Form.Item>

        <Form.Item
          style={{ width: '28%' }}
          className="form-item"
          name="course_id"
          label="选择课程"
          rules={[{ required: true }]}
        >
          <Select
            className="sel"
            size="middle"
            placeholder="请选择"
            onChange={changeCourse.bind(this)}
          >
            {projectName.map((item: any, i: number) => {
              return (
                <Option value={item.id} key={i}>
                  {item.name}
                </Option>
              );
            })}
          </Select>
        </Form.Item>

        {responsibility === 'ok' ? (
          <Form.Item
            style={{ width: '28%' }}
            className="form-item"
            name="type"
            label="作业类型"
            rules={[{ required: true }]}
          >
            <Select className="sel" size="middle" placeholder="请选择">
              <Option value="1">日常作业</Option>
              <Option value="2">阶段性交付作业</Option>
              <Option value="3">最终交付作业</Option>
            </Select>
          </Form.Item>
        ) : null}
        {responsibility === 'no' ? (
          <Form.Item
            style={{ width: '28%' }}
            className="form-item"
            name="type"
            label="作业类型"
            rules={[{ required: true }]}
          >
            <Select className="sel" size="middle" placeholder="请选择">
              <Option value="1">日常作业</Option>
            </Select>
          </Form.Item>
        ) : null}

        <Form.Item
          style={{ width: '90%' }}
          className="form-item"
          name="p_g_id"
          label="选择小组"
          tooltip={{
            title:
              '请选择该作业对应的学生分组，若仅选择分组未选择具体学生，则含义为选择了该分组下所有学生',
            icon: <InfoCircleOutlined />,
            color: 'blue',
          }}
        >
          <Select
            className="sel"
            size="middle"
            placeholder="请先选择课程，可多选"
            mode="multiple"
            allowClear
            onChange={changeGroup.bind(this)}
          >
            {grouptName.map((item: any, i: number) => {
              return (
                <Option value={item.id} key={i}>
                  {item.name}
                </Option>
              );
            })}
          </Select>
        </Form.Item>

        <Form.Item
          style={{ width: '90%' }}
          className="form-item"
          name="s_id"
          label="选择学生"
        >
          <Select
            className="sel"
            size="middle"
            placeholder="请选择，可多选"
            mode="multiple"
            allowClear
          >
            {studentList.map((item: any, i: number) => {
              return (
                <Option value={item.id} key={i}>
                  {item.userName}
                </Option>
              );
            })}
          </Select>
        </Form.Item>

        <Form.Item
          className="form-item"
          name="upload"
          label="相关附件"
          valuePropName="fileList"
          getValueFromEvent={normFile}
        >
          <Upload name="logo" action="/upload.do" listType="picture">
            <Button className="ant-btn ant-btn-primary addLeave">
              上传附件
            </Button>
          </Upload>
        </Form.Item>

        {/* 富文本 */}
        <Form.Item className="form-item1" name="work_content">
          <div className="editor">
            <Editor
              // editorState={editorState}
              wrapperClassName="demo-wrapper"
              editorClassName="demo-editor"
              editorState={editorState}
              onContentStateChange={onEditorChange} //获取内容变化值
              onEditorStateChange={onEditorStateChange} //编辑器状态发生变化时
              // onEditorStateChange={this.onEditorStateChange}
            />
          </div>
        </Form.Item>

        <Form.Item className="form-item1">
          <Button type="primary" htmlType="submit">
            确认发布
          </Button>
          <Modal
            title="发布作业"
            visible={visible}
            onOk={handleOk}
            confirmLoading={confirmLoading}
            onCancel={handleCancel}
          >
            <p>{modalText}</p>
          </Modal>
          <Button className="reset" htmlType="button" onClick={onReset}>
            重置
          </Button>
          <Button
            className="reset"
            htmlType="button"
            onClick={() => {
              history.push('/teacher/work/arrange');
            }}
          >
            取消
          </Button>
        </Form.Item>
      </Form>
    </div>
  );
};

export default addWork;
